package com.applancer.nativecmsflip;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.applancer.appInterface.ViewPagerEventInteface;
import com.applancer.dataprovider.DataProvider;
import com.applancer.delegate.NewFeedDelegate;
import com.applancer.fragment.FeedGeneralFragment;
import com.applancer.fragment.NavigationDrawerFragment;
import com.applancer.fragment.RightMenuFragment;
import com.applancer.model.HashKey;
import com.applancer.model.UserModel;
import com.applancer.model.WeatherModel;
import com.applancer.parser.WeatherParser;
import com.applancer.provider.ContentManager;
import com.applancer.provider.GPSTracker;
import com.applancer.provider.SystemBarTintManager;
import com.applancer.ui.CustomViewPager;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class MainActivity extends Activity implements
		NavigationDrawerFragment.NavigationDrawerCallbacks, NewFeedDelegate,
		ViewPagerEventInteface {

	public static final String MYPREFERENCES = "LoginRef";
	public static final String LOG_USERNAME = "login_username";
	public static final String LOG_PASS = "login_pass";
	public static final String LOG_EMAIL = "login_email";
	public static final String LOG_URL = "login_url";

	public static final String EXTRA_MESSAGE = "message";
	public static final String PROPERTY_REG_ID = "registration_id";
	private static final String PROPERTY_APP_VERSION = "appVersion";
	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

	private String SENDER_ID = "409122136060";

	public SharedPreferences sharedpreferences;
	protected GPSTracker gps;
	protected DataProvider dataprovider;

	protected DrawerLayout drawerLayout;

	protected MyTask task;
	protected Timer timer;
	protected Boolean bookmarksAdded;

	/**
	 * Fragment managing the behaviors, interactions and presentation of the
	 * navigation drawer.
	 */
	private NavigationDrawerFragment mNavigationDrawerFragment;
	private RightMenuFragment mNavigationDrawerFragmentRight;

	/**
	 * Used to store the last screen title. For use in
	 * {@link #restoreActionBar()}.
	 */
	private CharSequence mTitle;

	protected Boolean doneGetWeather;

	private CustomViewPager mPager;

	private FragmentStatePagerAdapter mPagerAdapter;

	private List<HashKey> listDataPager;

	protected GoogleCloudMessaging gcm;
	protected String regid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initial();
		execution();
	}

	private void initial() {
		mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager()
				.findFragmentById(R.id.navigation_drawer);
		mNavigationDrawerFragmentRight = (RightMenuFragment) getFragmentManager()
				.findFragmentById(R.id.right_drawer);

		drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

		mTitle = getTitle();

		sharedpreferences = getSharedPreferences(MYPREFERENCES,
				Context.MODE_PRIVATE);

		doneGetWeather = false;

		task = new MyTask();
		timer = new Timer();

		listDataPager = new ArrayList<HashKey>();
		mPager = (CustomViewPager) findViewById(R.id.pager);
		bookmarksAdded = false;
	}

	private void execution() {

		int actionBarTitleId = Resources.getSystem().getIdentifier(
				"action_bar_title", "id", "android");
		if (actionBarTitleId > 0) {
			TextView title = (TextView) findViewById(actionBarTitleId);
			if (title != null) {
				title.setEllipsize(TruncateAt.MARQUEE);
				title.setMarqueeRepeatLimit(-1);
				title.setSelected(true);
			}
		}

		listDataPager.add(new HashKey(getString(R.string.home_id),
				getString(R.string.home), 0, 0));

		// listDataPager.add(new HashKey(getString(R.string.bookmark_id),
		// getString(R.string.book_mark), -1, -1));

		mPager.setOnPageChangeListener(onpagechange);

		mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager(),
				listDataPager);
		// mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager(),
		// listDataPager);
		mPager.setAdapter(mPagerAdapter);
		onSectionAttached("Home");

		mNavigationDrawerFragment.setUp(R.id.navigation_drawer, drawerLayout);
		mNavigationDrawerFragmentRight.setUp(R.id.right_drawer, drawerLayout);

		UserModel umodel = new UserModel();
		umodel.setUserName(sharedpreferences.getString(LOG_USERNAME, ""));
		umodel.setEmail(sharedpreferences.getString(LOG_EMAIL, ""));
		umodel.setUrl(sharedpreferences.getString(LOG_URL, ""));
		umodel.setPass(sharedpreferences.getString(LOG_PASS, ""));

		ContentManager manager = ContentManager.getInstance();
		manager.currentUser = umodel;
		dataprovider = new DataProvider(this);

		SystemBarTintManager tintManager = new SystemBarTintManager(this);
		tintManager.setStatusBarTintEnabled(true);
		tintManager.setNavigationBarTintEnabled(true);

		tintManager.setStatusBarTintResource(R.color.statusbar_bg);
		tintManager.setNavigationBarTintResource(R.color.actionbar_bg);
	}

	public void onExecuteloadingList(List<HashKey> list) {

		listDataPager.addAll(list);
		listDataPager.add(new HashKey(getString(R.string.bookmark_id),
				getString(R.string.book_mark), -1, -1));
		bookmarksAdded = true;
		mPagerAdapter.notifyDataSetChanged();
	}

	private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {

		protected List<HashKey> ldata;

		public ScreenSlidePagerAdapter(FragmentManager fm, List<HashKey> data) {
			super(fm);
			ldata = data;
		}

		@Override
		public Fragment getItem(int position) {

			HashKey key = ldata.get(position);
			FeedGeneralFragment fragment = FeedGeneralFragment.createInstance(
					key.getId(), key.getTitle());
			return fragment;

		}

		// @Override
		// public int getItemPosition(Object object) {
		// MyFragment fragment = (MyFragment)object;
		// String title = fragment.getTitle();
		// int position = titles.indexOf(title);
		//
		// if (position >= 0) {
		// return position;
		// } else {
		// return POSITION_NONE;
		// }
		// }

		@Override
		public int getCount() {
			return ldata.size();
		}
	}

	OnPageChangeListener onpagechange = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int arg0) {
			HashKey key = listDataPager.get(arg0);

			onSectionAttached(key.getTitle());

			mNavigationDrawerFragment.setSelectedItemFocus(key.getGroup_pos(),
					key.getChild_pos());

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}
	};

	public class MyTask extends TimerTask {

		@Override
		public void run() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					retrieveWeather();
				}
			});

		}

	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {

		super.onConfigurationChanged(newConfig);

		mNavigationDrawerFragment.setUp(R.id.navigation_drawer, drawerLayout);
		mNavigationDrawerFragmentRight.setUp(R.id.right_drawer, drawerLayout);
		mNavigationDrawerFragment.fixListView();
		mNavigationDrawerFragmentRight.fixListView();

	}

	@Override
	public void onNavigationDrawerItemSelected(String id, String title) {

		if (id.equals(getString(R.string.bookmark_id)) && !bookmarksAdded) {
			listDataPager.add(new HashKey(getString(R.string.bookmark_id),
					getString(R.string.book_mark), -1, -1));
			mPagerAdapter.notifyDataSetChanged();
		}

		onSectionAttached(title);

		int i;
		for (i = 0; i < listDataPager.size(); i++) {
			if (listDataPager.get(i).getId().equals(id))
				break;
		}

		mPager.setCurrentItem(i, false);

		// FragmentManager fragmentManager = getFragmentManager();
		//
		// FeedGeneralFragment fragment = FeedNormalFragment.createInstance(id,
		// title);
		//
		// fragmentManager.beginTransaction().replace(R.id.container, fragment)
		// .commitAllowingStateLoss();
	}

	public void onSectionAttached(String tilte) {
		mTitle = tilte;
		restoreActionBar();
	}

	public void restoreActionBar() {
		ActionBar actionBar = getActionbar();
		actionBar.setTitle(mTitle);
	}

	private ActionBar getActionbar() {
		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		return actionBar;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!mNavigationDrawerFragment.isDrawerOpen()) {
			getMenuInflater().inflate(R.menu.main, menu);

			return true;
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();

		if (id == android.R.id.home) {
			drawerLayout.closeDrawer(Gravity.END);
		}

		if (id == R.id.action_settings) {
			return true;
		}

		if (id == R.id.action_user) {
			Log.d(this.getClass().toString(), "user action");

			// Intent i = new Intent(this, UserActivity.class);
			// startActivity(i);
			//
			// overridePendingTransition(R.anim.slide_left_in,
			// R.anim.slide_left_out);
			mNavigationDrawerFragmentRight.showMenu();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void updateTitle(String title) {

	}

	@SuppressLint("InlinedApi")
	@Override
	protected void onResume() {

		if (timer != null) {
			task = new MyTask();
			timer = new Timer();
			if (doneGetWeather) {
				timer.schedule(task, 1000 * 60 * 60, 1000 * 60 * 60);
			} else {
				timer.schedule(task, 0, 1000 * 60 * 60);
			}
		}
		
		if (checkPlayServices()) {
			gcm = GoogleCloudMessaging.getInstance(this);
			regid = getRegistrationId(this);
			Log.e("regID----------------", regid);

			if (regid.isEmpty()) {
				registerInBackground();
			}
		} else {

			Log.i(this.getClass().toString(),
					"No valid Google Play Services APK found.");
		}

		super.onResume();

	}

	private void registerInBackground() {
		new AsyncTask<String, String, String>() {
			protected void onPreExecute() {
			};

			protected void onPostExecute(String result) {
			};

			@Override
			protected String doInBackground(String... params) {
				String msg = "";
				try {
					if (gcm == null) {
						gcm = GoogleCloudMessaging
								.getInstance(MainActivity.this);
					}
					regid = gcm.register(SENDER_ID);
					Log.e("regID----------------", regid);
					msg = "Device registered, registration ID=" + regid;

					sendRegistrationIdToBackend();

					storeRegistrationId(MainActivity.this, regid);
				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();
				}
				return msg;
			}
		}.execute(null, null, null);
	}

	protected void storeRegistrationId(MainActivity mainActivity, String regid2) {
		final SharedPreferences prefs = getGCMPreferences(MainActivity.this);
		int appVersion = getAppVersion(MainActivity.this);
		Log.i(this.getClass().toString(), "Saving regId on app version "
				+ appVersion);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(PROPERTY_REG_ID, regid);
		editor.putInt(PROPERTY_APP_VERSION, appVersion);
		editor.commit();
	}

	private void sendRegistrationIdToBackend() {
		DataProvider datapro = new DataProvider(this);
		datapro.sendRegistrationIdToBackend(regid, handlerSend2backend);
	}

	AsyncHttpResponseHandler handlerSend2backend = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			Log.d("mainactivity", "Success");
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			Log.d("mainactivity", "Success");
		}
	};

	private SharedPreferences getGCMPreferences(Context context) {
		// This sample app persists the registration ID in shared preferences,
		// but
		// how you store the regID in your app is up to you.
		return getSharedPreferences(MainActivity.class.getSimpleName(),
				Context.MODE_PRIVATE);
	}

	private String getRegistrationId(Context context) {
		final SharedPreferences prefs = getGCMPreferences(context);
		String registrationId = prefs.getString(PROPERTY_REG_ID, "");
		if (registrationId.isEmpty()) {
			Log.i(this.getClass().toString(), "Registration not found.");
			return "";
		}

		int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION,
				Integer.MIN_VALUE);
		int currentVersion = getAppVersion(context);
		if (registeredVersion != currentVersion) {
			Log.i(this.getClass().toString(), "App version changed.");
			return "";
		}
		return registrationId;
	}

	private static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			throw new RuntimeException("Could not get package name: " + e);
		}
	}

	private boolean checkPlayServices() {

		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this,
						PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Log.i(this.getClass().toString(),
						"This device is not supported.");
				finish();
			}
			return false;
		}
		return true;
	}

	protected void onPause() {
		super.onPause();
		if (timer != null)
			timer.cancel();
	};

	private void retrieveWeather() {
		gps = new GPSTracker(MainActivity.this);
		(new Handler()).postDelayed(new Runnable() {

			@Override
			public void run() {
				if (gps.canGetLocation()) {

					double latitude = gps.getLatitude();
					double longitude = gps.getLongitude();
					if (latitude == 0 && longitude == 0) {

						gps.showSettingsAlert();

					} else
						dataprovider.getwoeid(longitude, latitude,
								handlerGetWoeid);
				} else {

					gps.showSettingsAlert();

				}

			}
		}, 5000);

	}

	AsyncHttpResponseHandler handlerGetWoeid = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

			if (arg2 == null)
				return;
			String str = new String(arg2);

			try {
				JSONObject object = new JSONObject(str);
				JSONObject query = object.getJSONObject("query");
				JSONObject results = query.getJSONObject("results");

				JSONObject solze;
				try {
					JSONArray Result = results.getJSONArray("Result");
					solze = Result.getJSONObject(0);
				} catch (Exception e) {
					solze = results.getJSONObject("Result");
				}

				String woeid = solze.getString("woeid");
				Log.d(this.getClass().toString(), "success" + woeid);

				dataprovider.getWeather(woeid, handlerGetWeather);

			} catch (Exception e) {

			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			Log.d(this.getClass().toString(), "fail");

		}
	};

	AsyncHttpResponseHandler handlerGetWeather = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

			doneGetWeather = true;
			if (arg2 == null)
				return;
			String str = new String(arg2);

			WeatherParser weatherparser = new WeatherParser();
			final WeatherModel weatherModel = weatherparser.parseWeather(str);

			runOnUiThread(new Runnable() {

				@Override
				public void run() {

					if (weatherModel.getCode() == null
							|| weatherModel.getCode().equals("")) {
						return;
					}

					LayoutParams lp = new LayoutParams(
							LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT, Gravity.RIGHT
									| Gravity.CENTER_VERTICAL);
					View customNav = LayoutInflater.from(MainActivity.this)
							.inflate(R.layout.weather_compound, null);

					customNav.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {

							Intent intent = new Intent(MainActivity.this,
									WeatherActivity.class);

							intent.putExtra("model", weatherModel);

							startActivity(intent);

						}
					});

					ImageView weatherpic = (ImageView) customNav
							.findViewById(R.id.weather_image);
					TextView temperature = (TextView) customNav
							.findViewById(R.id.weather_temperature);
					TextView textWeather = (TextView) customNav
							.findViewById(R.id.weather_text);

					temperature.setText(weatherModel.getTemperature_top());
					textWeather.setText(weatherModel.getWeather_sumary());

					try {
						InputStream ims = getAssets().open(
								"weather_icon/weather_"
										+ weatherModel.getCode() + ".png");
						Drawable d = Drawable.createFromStream(ims, null);
						weatherpic.setImageDrawable(d);
					} catch (Exception e) {

					}

					// Picasso.with(MainActivity.this)
					// .load(weatherModel.getIconURL())
					// .placeholder(null)
					// .error(R.drawable.ic_launcher)
					// .resizeDimen(R.dimen.actionbar_image_size,
					// R.dimen.actionbar_image_size)
					// .centerInside().into(weatherpic);

					getActionbar().setCustomView(customNav, lp);
					getActionbar().setDisplayShowCustomEnabled(true);
				}

			});

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			Log.d(this.getClass().toString(), "fail");

		}
	};

	@Override
	public void onFreezeViewPager() {
		mPager.setPagingEnabled(false);
	}

	@Override
	public void onReleaseViewPager() {
		mPager.setPagingEnabled(true);
	}

}
